﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using MvcSystemsCommander.Extensions.Security;
using MvcSystemsCommander.Models.ViewModel;
using System.Web.Script.Serialization;
using System.Web.Security;

namespace MvcSystemsCommander.Controllers
{
    public class AccountController : Controller
    {
        //
        // GET: /Account/

        public ActionResult Index()
        {
            return Login();
        }

        [HttpGet]
        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login(LoginInputModel m)
        {
            if (ModelState.IsValid)
            {
                if (m.IsValid(m.Username, m.Password))
                {
                    MSCPrincipalSerializeModel serializeModel = new MSCPrincipalSerializeModel();
                    serializeModel.Username = m.Username;
                    JavaScriptSerializer serializer = new JavaScriptSerializer();
                    string userData = serializer.Serialize(serializeModel);

                    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                        1,
                        m.Username,
                        DateTime.Now,
                        DateTime.Now.AddMinutes(15),
                        false,
                        userData);

                    string encodedTicket = FormsAuthentication.Encrypt(ticket);
                    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encodedTicket);
                    Response.Cookies.Add(cookie);

                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", "Your username or password was incorrect.");
                }
            }

            return View(m);
        }

    }
}
